package com.nx.samuel.callback_demo.provider.impl;

import com.nx.samuel.callback_demo.api.CallbackListener;
import com.nx.samuel.callback_demo.api.CallbackService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class CallbackServiceImpl implements CallbackService {

    private final Map<String, CallbackListener> listenerMap;

    public CallbackServiceImpl() {
        listenerMap = new ConcurrentHashMap<>();

        Thread t = new Thread(() -> {
            while (true) {
                try {
                    for (Map.Entry<String, CallbackListener> entry : listenerMap.entrySet()) {
                        try {
                            entry.getValue().changed(getChanged(entry.getKey()));
                        } catch (Throwable t1) {
                            listenerMap.remove(entry.getKey());
                        }
                    }
                    Thread.sleep(5000); // timely trigger change event
                } catch (Throwable t1) {
                    t1.printStackTrace();
                }
            }
        });
        t.setDaemon(true);
        t.start();
    }

    @Override
    public void addListener(String key, CallbackListener listener) throws InterruptedException {
        //记录回调
        listenerMap.put(key, listener);
        System.out.println("执行正常的业务逻辑"+new Date());
        TimeUnit.MILLISECONDS.sleep(500);
    }

    private String getChanged(String key) {
        return "Changed: " + new Date();
    }
}
